class Main extends eui.UILayer {
    protected createChildren(): void {
        super.createChildren();
        App.UiManager;
        /**初始游戏层级关系 */
        this.addChild(GameLayer.getInstance());
        //生命周期管理器
        this.addLifeCycle();
        /**初始化数据 */
        this.initData();
        // 添加监听
        this.addListeners();
        /**登录 */
        this.loginGame();
        /**加载素材配置等信息，登录和素材都加载完毕后就进入home页面 */
        this.runGame().catch(e => {
            console.log(e);
        });
    }

    /********************1、生命周期管理器 ********************/
    private addLifeCycle() {
        /***********添加白鹭的生命周期 */
        egret.lifecycle.onPause = () => {
            egret.ticker.pause();
            GameConfig.isGameOnShowing = false;
            SoundManager.pauseBgMusic();
        }
        egret.lifecycle.onResume = () => {
            egret.ticker.resume();
            GameConfig.isGameOnShowing = true;
            SoundManager.restartBgMusic();
        }
        /***********设置分享可以携带shareTicket */
        platform.callPlatformMethod("showShareMenu",{withShareTicket: true});
        platform.callPlatformMethod("updateShareMenu",{withShareTicket: true});

        /***********添加微信的生命周期--展示可见的时候 */
        platform.callPlatformMethod("onShow",(data)=>{
            GameConfig.isGameOnShowing = true;
            var query = data.query;
            GameConfig.showGroupRank = (query.showRank == "true");
            GameConfig.query = data.query;
            GameConfig.shareTicket = data.shareTicket;
            // 发布
            GameConfig.launchData = data;
            App.EventManager.dispatchEvent(GameConstants.GAME_ACTIVE);
            SoundManager.restartBgMusic();
            this.onLauchOfLifeCircle(data);
        });
        /***********添加微信的生命周期--不可见的时候，关闭或进入设置等情形下 */
        platform.callPlatformMethod("onHide",(data)=>{

            GameConfig.isGameOnShowing = false;
            App.EventManager.dispatchEvent(GameConstants.GAME_HIDE);
            SoundManager.pauseBgMusic();
        });
        /***********添加微信的生命周期-点击右上角的。。。->转发 */
        platform.callPlatformMethod("onShareAppMessage",(data)=>{
            // 策略A
            let query = {from:GameConfig.shareFrom.topRightMore};
            let shareData = GameConfig.getShareData(GameConfig.shareInfoA,query);
            return shareData;
        });
    }
    /**生命周期里的第一次启动 */
    private onLauchOfLifeCircle(data:any){
        if(!GameConfig.isFirstLaunch){
            return;
        }
        GameConfig.isFirstLaunch = false;
        
        
    }

    /********************2、初始化数据信息 ********************/
    private initData() {
        /**基础设置 */
        GameConfig.stageWidth = egret.MainContext.instance.stage.stageWidth;
        GameConfig.stageHeight = egret.MainContext.instance.stage.stageHeight;
        platform.getSystemInfo({success:function(res){
            GameConfig.systemInfo = res;
            GameConfig.scale = res.screenWidth / GameConfig.stageWidth;
            GameConfig.SDKVersion = res.SDKVersion;
            //排行榜兼容
            GameConfig.showRank = StringUtil.sdkVersionCompare(GameConfig.SDKVersion, "1.9.92");
            GameConfig.showGameScenceRank = StringUtil.sdkVersionCompare(GameConfig.SDKVersion, "2.0.0");
        }});
        /**请求接口切换 */
        if (GameConfig.isRelease) {
            GameConfig.requestUrl = "https://wxapp.xyhuyu.cn/upstorey/";
        } else {
            GameConfig.requestUrl = "https://wxapp.xyhuyu.cn/upstorey/";
        }
        // 使用上次登录过的cookie
        GameConfig.requestHead = null;
        // 初始化缓存过的用户信息，让数据显示更快速及时
        UserData.initData();
        
    }
    // 添加监听
    private addListeners(){
        App.EventManager.addEventListener(GameConstants.GAME_ACTIVE,this.requestShareReport,this);
    }
    // 每次重新显示时的处理
    private requestShareReport()
    {
        if(GameConfig.launchData && GameConfig.launchData.query){
            let shareId = GameConfig.launchData.query.id;
            let shareFrom = GameConfig.launchData.query.from;
            if(!shareId || !shareFrom)return;
            if(shareFrom != GameConfig.shareFrom.invitePageGiveFriend2Share &&
                shareFrom != GameConfig.shareFrom.invitePageReqFriend2Share &&
                shareFrom != GameConfig.shareFrom.invitePageWatchVideo2Share){
                return;
            }
            let params = {sharer_id:shareId,from:shareFrom};
            App.HttpRequestManager.request(NetConstants.SHARE_REPORT,
                                            params, 
                                            this.responseShareReport.bind(this));
        }

    }
    private responseShareReport(res)
    {

    }
    /********************3、登录 ********************/
    private async loginGame() {
        GameConfig.requestHead = null;
         if(GameConfig.requestHead){
             // 有请求头cookie了，表示之前已经登录过了，直接请求用户信息
            this.getUserInfo();
             return;
         }
         // 调用登录
         App.login(this.responseLogin.bind(this));
    }
    // 响应登录数据
    private responseLogin(res: any) {
        if (res.statusCode == 200 && res.data.code == 0) {
            // 请求用户信息
            this.getUserInfo();
        } else {
            
        }
    }
    //请求用户信息
    private getUserInfo() {
        App.HttpRequestManager.request(NetConstants.GET_INFO, "", this.responseUserInfo.bind(this),egret.HttpMethod.GET)
    }
    //处理用户信息
    private responseUserInfo(res) {
        if (res.statusCode == 200 && res.data.code == 0) {
            UserData.saveUserInfo(res.data.data);
            // 获取用户信息成功后进入首页
            UserData.isLogin = true;
            this.createGameScene();
        } else {
           
        }
    }
    /***************4、加载资源文件 *******************/
    private loadResourceSuccess = false;
    private async runGame() {
        /**注入自定义的素材解析器*/
        let assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());
        /**加载 */
        await this.loadResource();
        this.loadResourceSuccess = true;
        // 资源加载完成后进入首页
        this.createGameScene();
    }
    // 加载资源文件
    private async loadResource() {
        try {
            await RES.loadConfig("resource/default.res.json", "resource/");
            await this.loadTheme();
            await RES.loadGroup("loading");
            App.EventManager.dispatchEvent(GameConstants.UI_ADD_TO_PARENT,GameConfig.uiIndex.load);
            await RES.loadGroup("game", 0, gameUi.loadScene);
            //await RES.loadGroup("preload", 0, gameUi.loadScene);
        }
        catch (e) {
            console.error(e);
        }
    }
    // 加载主题
    private loadTheme() {
        return new Promise((resolve, reject) => {
            // load skin theme configuration file, you can manually modify the file. And replace the default skin.
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            let theme = new eui.Theme("resource/default.thm.json", this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, () => {
                resolve();
            }, this);
        })
    }
    /***************5、进入游戏 *******************/
    
    /**
     * 创建场景界面
     * Create scene interface
     */
    private createGameScene(): void {
         if(!UserData.isLogin || !this.loadResourceSuccess)return;
         //if(!this.loadResourceSuccess)return;
         // 向共享数据域发送命令加载一遍朋友关系链数据
         this.loadFriendsRankData();
        App.EventManager.dispatchEvent(GameConstants.UI_REMOVE_FROM_PARENT,GameConfig.uiIndex.load);
         App.EventManager.dispatchEvent(GameConstants.UI_ADD_TO_PARENT,GameConfig.uiIndex.home);
        //App.EventManager.dispatchEvent(GameConstants.UI_ADD_TO_PARENT,GameConfig.uiIndex.game);
    }
    /**
     * 提前加载一遍朋友关系链数据
     */
    private loadFriendsRankData() {
        OpenDataUtil.postMessage({
            status: GameConfig.shareCavansCommand.GET_FRIEND_INFO,
            mine: UserData.getMineOpenData(),
        });
    }
}
